//index.js
//获取应用实例
var app = getApp()
Page({
  data: {
    sortType: 6,
    showLoading: true,
    noMoretip: false,
    page: 0,
    curListType: 2,
    pricesort: '',
    allGoodsList:[
      {},
      {       //价格排序
        pageUp:0,
        pageDown: 0,
        noMoretipUp: false,
        noMoretipDown: false,
        goodsListUp:[],
        goodsListDown:[]
      },
      {      //销量排序
        page: 0,
        noMoretip: false,
        goodsList: [],
        
      },
      {},
      {},
      {      //新品排序
        page: 0,
        noMoretip: false,
        goodsList: [],
        
      },
      {      //综合排序
        page: 0,
        noMoretip: false,
        goodsList: [],
      },
      

    ],   //存放所有分类商品内容，页码
  },
  onLoad: function (e) {
    var that = this;
    var oneid = that.data.oneid;
    var secondid = that.data.secondid;
    if (e && e.oneid) {
      oneid = e.oneid;
      that.setData({
        oneid: oneid
      })
    }
    if (e && e.secondid) {
      secondid = e.secondid;
      that.setData({
        secondid: secondid
      })
    }
    if (e && e.title) {
      that.setData({
        title: e.title
      })
      app.setNavtitle(e.title);
    }
    if (e && e.enterfrom) {
      var enterfrom = e.enterfrom == 'share' ? true : false;
      that.setData({
        enterfrom: enterfrom
      })
    }
    app.setNavColor(that);
    that.requestAllGoods(oneid, secondid);
  },
  onShow: function () {
    var that = this;
    var title = '全部商品';
    if (that.data.title) {
      title = that.data.title;
    }
    app.setNavtitle(title);
    app.setCartnum();//更新购物车数量
  },
  requestAllGoods: function (oneid, secondid) {
    
    var that = this;
    
    var data = {};
    
    var sortType = that.data.sortType;
    console.log(that.data.allGoodsList[sortType]);
    var page = that.data.page;
    data.map = 'applet_goods_list';
    data.sortType = sortType;
    var pricesort = that.data.pricesort;
    data.priceSort = pricesort;
    if (oneid) {
      data.kind1 = oneid;
    }
    data.kind2 = secondid;
    data.page = page;
    console.log(data);
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res.data);
        that.setData({
          flLink: res.data.link
        })
        if (res.data.ec == 200) {
          var curArr = res.data.data;
          var lastPageLength = curArr.length;
          if (page == 0) {
            that.setData({
              shopGoodsArr: null
            })
          }
          var shopGoodsArr = that.data.shopGoodsArr ? that.data.shopGoodsArr : [];
          var shopGoodsLen = shopGoodsArr.length;
          if (curArr.length>0){
            that.setData({
              [`shopGoodsArr[${shopGoodsLen}]`]: curArr
            })
          } else if (page == 0) {
            that.setData({
              shopGoodsArr: []
            })
          }
          console.log(that.data.shopGoodsArr)
          if (lastPageLength < 10) {
            that.setData({
              noMoretip:true,
              showLoading: false
            });
          }
          var noMoretip=that.data.noMoretip
          if (sortType == 1) {
            if (pricesort == 'up') {
              that.setData({
                [`allGoodsList[${sortType}].goodsListUp`]: that.data.shopGoodsArr,
                [`allGoodsList[${sortType}].noMoretipUp`]: noMoretip,
              })
            } else {
              that.setData({
                [`allGoodsList[${sortType}].goodsListDown`]: that.data.shopGoodsArr,
                [`allGoodsList[${sortType}].noMoretipDown`]: noMoretip,
              })
            }
          } else {
            that.setData({
              [`allGoodsList[${sortType}].goodsList`]: that.data.shopGoodsArr,
              [`allGoodsList[${sortType}].noMoretip`]: noMoretip,
            })
          }
          console.log(that.data.allGoodsList);
        } else {
          console.log(res.data)
          if (page <= 0) {
            that.setData({
              shopGoodsArr: []
            })
          } else {
            that.setData({
              [`allGoodsList[${sortType}].noMoretip`]: true,
              showLoading: false,
              noMoretip:true
            });
          }
        }
      },
      complete: function () {
        wx.stopPullDownRefresh();
      }
    });
  },
  onPullDownRefresh: function () {
    var that = this;
    var oneid = that.data.oneid;
    var secondid = that.data.secondid;
    that.setData({
      page: 0,
      noMoretip: false,
      showLoading: true
    });
    that.requestAllGoods(oneid, secondid);
    console.log("下拉刷新");
  },
  onReachBottom: function () {
    var that = this;
    var oneid = that.data.oneid;
    var secondid = that.data.secondid;
    console.log("到达页面底部")
    var isMore = that.data.noMoretip;
    var page = that.data.page;
    var sortType = that.data.sortType;
    var pricesort = that.data.pricesort;
    page++;
    if (sortType == 1) {
      if (pricesort == 'up') {
        that.setData({
          [`allGoodsList[${sortType}].pageUp`]: page
        })
      } else {
        that.setData({
          [`allGoodsList[${sortType}].pageDown`]: page
        })
      }
    } else {
      that.setData({
        [`allGoodsList[${sortType}].page`]: page
      })
    }
    that.setData({
      page: page
    });
    if (isMore) {
      console.log("已完成或正在加载");
    } else {
      that.requestAllGoods(oneid, secondid);
    }
  },
  goodDetail: function (e) {
    var goodId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/goodDetail/goodDetail?id=' + goodId
    })
  },
  changeShowType: function (e) {
    var type = e.target.dataset.type;
    this.setData({
      showType: type
    })
  },
  allflgoodPage: function (e) {
    var link = e.currentTarget.dataset.link;
    wx.navigateTo({
      url: link
    })
  },
  searchPage: function () {
    wx.navigateTo({
      url: '/pages/searchList/searchList'
    })
  },
  sortGood: function (e) {
    var that = this;
    var sortType = e.target.dataset.sort;
    var pricesort = that.data.pricesort;
    var allGoodsList = that.data.allGoodsList;
    console.log(that.data.allGoodsList,sortType)
    if (sortType == 1) {
      if (pricesort == 'up') {
        pricesort = 'down';
        var page = allGoodsList[sortType].pageDown;
        var noMoretip = allGoodsList[sortType].noMoretipDown;
        var shopGoodsArr = allGoodsList[sortType].goodsListDown
      } else {
        pricesort = 'up';
        var page = allGoodsList[sortType].pageUp;
        var noMoretip = allGoodsList[sortType].noMoretipUp;
        var shopGoodsArr =allGoodsList[sortType].goodsListUp
      }
    } else {
      pricesort = '';
      var page = allGoodsList[sortType].page;
      var noMoretip = allGoodsList[sortType].noMoretip;
      var shopGoodsArr = allGoodsList[sortType].goodsList;
    }
    this.setData({
      sortType: sortType,
      pricesort: pricesort,
      page: page,
      noMoretip: noMoretip
    })
    if (noMoretip){
      this.setData({
        showLoading:false
      })
    }
    if (page == 0 && !noMoretip){
      this.onPullDownRefresh();
    }else{
      
      this.setData({
        shopGoodsArr: shopGoodsArr
      })
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 0
      })
    }
   
  },
  toggleListshow: function () {
    var that = this;
    var curListType = that.data.curListType;
    if (curListType == 2) {
      curListType = 4;
    } else if (curListType == 4) {
      curListType = 2;
    }
    that.setData({
      curListType: curListType
    })
  },
  addminusCart: function (e) {
    var that = this;
    var curgood = e.currentTarget.dataset.curgood;
    var smallNum = curgood.smallNum;
    that.setData({
      curgood: curgood,
      buyNumber: smallNum,
      curImgformat: '',
      chooseGuige: {
        stock: curgood.stock
      },
      isShowFormat: true
    })
  },
  hideFormat: function () {
    var that = this;
    that.setData({
      isShowFormat: false
    })
  },
  stoptouchmove: function (e) {
    console.log(e);
  },
  //单张图片预览
  singlePeiviewImg: function (e) {
    var curimg = e.currentTarget.dataset.curimg;
    var imgs = new Array(e.currentTarget.dataset.imgs);
    wx.previewImage({
      current: curimg, // 当前显示图片的http链接
      urls: imgs // 需要预览的图片http链接列表
    })
  },
  chooseGuige: function (e) {
    var that = this;
    var findex = e.target.dataset.findex;
    var index = e.target.dataset.index;
    var curgood = that.data.curgood;
    if (findex == 0) {
      var curImgformat = curgood.formatList[0].value[index];
      that.setData({
        curImgformat: curImgformat
      })
    }
    var checkFormat = [];
    for (var i = 0; i < curgood.formatList[findex].value.length; i++) {
      curgood.formatList[findex].value[i].checked = false;
    }
    curgood.formatList[findex].value[index].checked = true;
    for (var i = 0; i < curgood.formatList.length; i++) {
      for (var j = 0; j < curgood.formatList[i].value.length; j++) {
        if (curgood.formatList[i].value[j].checked) {
          checkFormat.push(curgood.formatList[i].value[j]);
        }
      }
    }
    that.setData({
      curgood: curgood,
      checkFormat: checkFormat
    })
    if (checkFormat.length == curgood.formatList.length) {
      var formatName = '';
      for (var i = 0; i < checkFormat.length; i++) {
        formatName += checkFormat[i].name;
      }
      console.log(formatName);
      var chooseGuige = curgood.formatValue[formatName];
      chooseGuige.formatName = formatName;
      chooseGuige.formatName = formatName;
      console.log(chooseGuige);
      that.setData({
        chooseGuige: chooseGuige
      })
    }
  },
  changeNum: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    var buyNum = parseInt(that.data.buyNumber);
    var stock = parseInt(that.data.chooseGuige.stock);
    var purchase = parseInt(that.data.curgood.purchase);
    var disabled = e.currentTarget.dataset.disable;
    if (disabled) return;
    if (type == 'add') {
      if (stock == 0) {
        app.errorTip(that, '商品库存不足', 2000);
      }
      if (buyNum < stock) {
        if (buyNum < purchase) {
          buyNum++;
        } else {
          app.errorTip(that, '超出限购数量', 2000);
        }
      } else {
        buyNum = stock;
      }
    } else {
      var smallNum = that.data.curgood.smallNum > 1 ? that.data.curgood.smallNum : 1;
      if (buyNum > smallNum) {
        buyNum--;
      } else {
        buyNum = smallNum;
      }
    }

    that.setData({
      buyNumber: buyNum
    })
  },
  numChange: function (e) {
    var that = this;
    var stock = that.data.chooseGuige.stock;
    var val = e.detail.value;
    val = val.replace(/\D/g, '');
    if ((parseInt(val)) > parseInt(stock)) {
      that.setData({
        buyNumber: stock
      })
    } else {
      that.setData({
        buyNumber: val
      })
    }
  },
  confirmAddcart: function (e) {
    var that = this;
    var curgoodCart = that.data.curgoodCart;
    var gid = e.currentTarget.dataset.gid;
    var gfid = that.data.chooseGuige.id;
    var num = parseInt(that.data.buyNumber);
    var isFormat = that.data.curgood.hasFormat;
    var stock = parseInt(that.data.chooseGuige.stock);
    var data = {
      map: 'applet_add_cart',
      gid: gid,
      gfid: gfid,
      num: num,
      add: 1
    }
    if (isFormat && !gfid) {
      app.errorTip(that, '请选择商品规格！', 2000);
      return;
    }
    if (!data.num || data.num <= 0) {
      app.errorTip(that, '请输入正确的商品数量', 2000);
      return;
    }
    console.log("库存数量" + stock);
    console.log("商品数量" + data.num);
    if (data.num > stock) {
      app.errorTip(that, '商品数量超出库存', 2000);
      return;
    }
    console.log(data);
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res.data);
        if (res.data.ec == 200) {
          that.setData({
            isShowFormat: false,
            cartNum: res.data.data.cartNum
          })
          that.hideFormat();
          app.errorTip(that, '已成功加入购物车', 2000);
          app.globalData.requestCartNum = res.data.data.cartNum;
          app.setCartnum();//更新购物车数量
        } else {
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
      }
    });
  },
  onShareAppMessage: function () {
    var that = this;
    var title = that.data.title ? that.data.title : '商品列表';
    var oneid = that.data.oneid ? that.data.oneid : '';
    var secondid = that.data.secondid ? that.data.secondid : '';
    app.getPoint(that);
    return {
      title: title,
      path: '/pages/allgoods/allgoods?enterfrom=share&oneid=' + oneid + '&secondid=' + secondid + '&title=' + title
    }
  }
})